package com.redrose.rxandroiddemo.json;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.TypeAdapter;
import com.google.gson.annotations.JsonAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;
import com.google.gson.stream.JsonWriter;
import com.redrose.rxandroiddemo.bean.Chapter;
import com.redrose.rxandroiddemo.bean.User;

import java.io.IOException;

public class UserJsonAdapter extends TypeAdapter<User> {
    @Override
    public void write(JsonWriter out, User value) throws IOException {
        if (value == null) {
            out.nullValue();
            return;
        }
        out.beginObject();
        out.name("name").value("RedRose");
        out.name("age").value(28);
        out.endObject();
    }

    @Override
    public User read(JsonReader in) throws IOException {
        if (in.peek() == JsonToken.NULL) {
            in.nextNull();
        }
        String name = "";
        int age = 0;
        in.beginObject();
        while (in.hasNext()) {
            switch (in.nextName()) {
                case "name":
                    name = in.nextString();

                    break;
                case "age":
                    age = in.nextInt();
                    break;
            }
        }
        in.endObject();
        return new User(name, age);
    }

    public static void main(String[] args) {
        writeObject();
        readObject();
    }

    private static void writeObject() {
        Gson gson = new GsonBuilder().create();
        User user = new User("qiububai", 26);
        String s = gson.toJson(user);
        System.out.println(s);
    }

    private static void readObject() {
        Gson gson = new GsonBuilder().create();
        String userString = "{\"name\":\"RedRose\",\"age\":28}";
        User user = gson.fromJson(userString, User.class);
        System.out.println(user);
    }
}
